package top.lyjwn.ajui.network;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import top.lyjwn.ajui.util.LogUtil;

/**
 * http回调
 */
public abstract class OnCallback implements Callback {
    private long beginTime;
    private long endTime;


    public OnCallback() {
        beginTime = new Date().getTime();
    }

    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {
        endTime = new Date().getTime();
        String path = call.request().url().url().getPath();
        LogUtil.i("http请求耗时", (endTime - beginTime) + "ms  路径:" + path,e);
        String msg = "";
        if (e instanceof ConnectException) {
            LogUtil.e("请求出错", "网络连接失败，请连接网络！",e);
            msg = "连接失败 没有网络接入";
        } else if (e instanceof UnknownHostException) {
            LogUtil.e("请求出错", "目标主机没有响应",e);
            msg = "网络迷路了";
        } else if (e instanceof SocketTimeoutException) {
            LogUtil.e("请求出错", "网络请求超时！",e);
            msg = "网络有点堵";
        } else {
            LogUtil.e("请求出错", "系统异常！" + e.getMessage(),e);
            msg = "未知的网络错误";
        }
        onResponse(false, 500, msg, e.getMessage());
        call.cancel();
    }

    @Override
    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
        endTime = new Date().getTime();
        String path = call.request().url().url().getPath();
        LogUtil.i("http请求耗时", endTime - beginTime + "ms  路径:" + path);
        Request request = response.request();
        HttpUrl httpUrl = request.url();
        URL url = httpUrl.url();
        ResponseBody body = response.body();
        String result = body.string();
        response.close();
        try {
            JSONObject jsonObject = JSONObject.parseObject(result);
            onResponse(jsonObject.getBooleanValue("done"), jsonObject.getInteger("code"), jsonObject.getString("msg"), jsonObject.getString("data"));
        } catch (Exception e) {
            if (e instanceof JSONException) {
                LogUtil.e("JSON装换异常:", "意外的错误" + e.getLocalizedMessage());
            }
            LogUtil.e("ERROR!! url ====> " + url.getPath(), "data_str  ====> " + result,e);
            onResponse(false, 500, e.getLocalizedMessage(), e.getMessage());
        }
    }

    /**
     * @param done 是否完成预期功能
     * @param code 状态码
     * @param msg  信息
     * @param data 数据
     */
    public abstract void onResponse(boolean done, Integer code, String msg, String data);

}
